package com.example.hello1;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.time.LocalDate;

public class currency extends AppCompatActivity implements Runnable {

    TextView currency_change;
    private static final String Tag = "currency_change";
    private static final String Tag2 = "多线程";
    private float eurorate = 0.28f;
    private float dollarrate = 0.21f;
    private float wonrate = 501;
    private  String ts="";
    //    LocalDate today = LocalDate.now();
//    LocalDate tomorrow = LocalDate.now().plusDays(1);
    Handler handler;
//    private final static long ONE_DAY_MSECOND = 24 * 60 * 60 * 1000;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_currency);

        //读取保存的数据
        SharedPreferences sp = getSharedPreferences("save_currency", Activity.MODE_PRIVATE);
        //PreferenceManager.getDefaultSharedPreferences(this);

            ts=sp.getString("updateStr","");
            dollarrate = sp.getFloat("dollar_rate", 0.0f);
            eurorate = sp.getFloat("euro_rate", 0.0f);
            wonrate = sp.getFloat("won_rate", 0.0f);
            Log.i(Tag, "get from xml");
            Log.i(Tag, "from xml dollarate" + dollarrate);
            Log.i(Tag, "from xml eurorate" + eurorate);
            Log.i(Tag, "from xml wonrate" + wonrate);

        //开启线程
        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                Log.i(Tag2, "开始接受消息");
                if (msg.what == 6) {
                    Bundle bda=(Bundle) msg.obj;

                    dollarrate=bda.getFloat("r1");
                    Log.i(Tag2,"dollarrate:"+dollarrate);
                    eurorate=bda.getFloat("r2");
                    Log.i(Tag2,"eurorate:"+eurorate);
                    wonrate=bda.getFloat("r3");
                    Log.i(Tag2,"wonrate:"+wonrate);

                }
                else{
                    String s = msg.obj.toString();
//                    float a=Float.parseFloat(s);s
//                    lista.add(a);
                    Log.i(Tag2, "收到的消息为:" + s);

               }
                super.handleMessage(msg);
            }
        };
        //
        Mycurrency_thred td = new Mycurrency_thred();
        td.setHadeler(handler);
        Thread t = new Thread(td);
        t.start();

    }

    public void currency(View view) {
        float num;
        String cur = "";
        Log.i(Tag2, "Onclilck calculate"); //日志设置
        //获取人名币数值
        EditText edit_number = findViewById(R.id.rmb);
        String rmb = edit_number.getText().toString();

        if (rmb.length() <= 0) {
            Toast.makeText(this, "请输入数据之后计算", Toast.LENGTH_SHORT).show();

        } else {

            float rmb_num = Float.parseFloat(rmb);
            if (view.getId() == R.id.dollar) {
                num = rmb_num * dollarrate;
                cur = num + "dollar";
            } else if (view.getId() == R.id.euro) {
                num = rmb_num * eurorate;
                cur = num + "euro";
            } else if (view.getId() == R.id.won) {
                num = rmb_num * wonrate;
                cur = num + "won";
            }
            //传递到显示页面
            TextView currency_change = findViewById(R.id.curency_show);
            currency_change.setText(cur);
        }
    }

    public void openOne(View btn) {
        Intent config = new Intent(this, currency_fetch.class);
        config.putExtra("dollar_rate", dollarrate);
        config.putExtra("euro_rate", eurorate);
        config.putExtra("won_rate", wonrate);
        Log.i(Tag, "prime dollar_rate:" + dollarrate); //日志设置
        Log.i(Tag, "prime euro_rate:" + eurorate); //日志设置
        Log.i(Tag, "prime won_rate:" + wonrate); //日志设置
        //startActivity(config);
        startActivityForResult(config, 505);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 505 && resultCode == 506) {

            dollarrate = data.getFloatExtra("dollar_rate", 0.1f);
            eurorate = data.getFloatExtra("euro_rate", 0.1f);
            wonrate = data.getFloatExtra("won_rate", 0.1f);
            Log.i(Tag, "result dollar_rate:" + dollarrate); //日志设置
            Log.i(Tag, "result euro_rate:" + eurorate); //日志设置
            Log.i(Tag, "result won_rate:" + wonrate); //日志设置

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override//多线程
    public void run() {
        Log.i(Tag2, "多线程程序开始");
        if (!ts.equals(LocalDate.now().toString())) {
            //获取网络数据
            URL url = null;
            Bundle bdl = new Bundle();
            LocalDate todayDate = LocalDate.now();
            String todayStr = todayDate.toString();
            try {
                Document doc2 = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
                Log.i(Tag2, "run:" + doc2.title());
                Log.i(Tag2, "today" + todayStr);
                Elements tables = doc2.getElementsByTag("table");
                Element table1 = tables.first();
                Elements hrefs = table1.getElementsByTag("tr");
                for (int i = 1; i < hrefs.size(); i++) {
                    Elements td = hrefs.get(i).getElementsByTag("td");
                    String cname = td.get(0).text();
                    String rate = td.get(5).text();

                    if ("美元".equals(cname)) {
                        bdl.putFloat("r1", 100f / Float.parseFloat(rate));
                    } else if ("欧元".equals(cname)) {
                        bdl.putFloat("r2", 100f / Float.parseFloat(rate));

                    } else if ("韩元".equals(cname)) {
                        bdl.putFloat("r3", 100f / Float.parseFloat(rate));

                    }

                    SharedPreferences sp = getSharedPreferences("save_currency", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    //PreferenceManager.getDefaultSharedPreferences(this);
                    editor.putFloat("dollar_rate", dollarrate);
                    editor.putFloat("euro_rate", eurorate);
                    editor.putFloat("won_rate", dollarrate);
                    editor.putString("updateStr", todayStr);
                    editor.apply();

                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            //发送消息给主线程
            Message msg = handler.obtainMessage();
            msg.what = 6;
            msg.obj = bdl;
            handler.sendMessage(msg);
            Log.i(Tag2, "睡眠1s之后传递消息");

        }
        else{

            Message msg = handler.obtainMessage();
            msg.what = 5;
            msg.obj = "不从网络获取数据";
            handler.sendMessage(msg);
            Log.i(Tag2, ""+msg.obj.toString());
        }
    }

    private String inputStream2String(InputStream in) throws IOException {
        final int bufsize = 1024;
        final char[] buf = new char[bufsize];
        StringBuilder out = new StringBuilder();
        Reader instream = new InputStreamReader(in, "gb2312");
        while (true) {
            int rsz = instream.read(buf, 0, buf.length);
            if (rsz < 0)
                break;
                out.append(buf, 0, rsz);
        }
        return out.toString();
    }


}